﻿@using Fluxor.Blazor.Web.Components
@using FormBuilder.Helpers
@using SimpleIdServer.IdServer.Website.Resources
@using SimpleIdServer.IdServer.Website.Stores.FormStore
@using SimpleIdServer.IdServer.Website.Stores.AcrsStore
@using FormBuilder.Components.Form
@using FormBuilder.Components
@using FormBuilder.Models.Layout
@using FormBuilder.Models
@using SimpleIdServer.IdServer.Website.Stores.LanguageStore
@using SimpleIdServer.IdServer.Website.Stores.TemplateStore
@using SimpleIdServer.IdServer.Website.Stores.WorkflowsStore
@inject IState<FormState> formState
@inject IState<TemplatesState> templatesState
@inject IState<TemplateState> templateState
@inject IState<WorkflowLayoutListState> workflowLayoutListState
@inject IState<LanguagesState> languagesState
@inject IDispatcher dispatcher
@inject IUrlHelper urlHelper
@inject NotificationService notificationService
@inject NavigationManager navigationManager
@inherits FluxorComponent

<RadzenText class="mt-3 mb-3 no-margin" Text="@formState.Value.Form?.Name" TextStyle="TextStyle.DisplayH3" />

<RadzenCardLoader Variant="Variant.Filled" IsLoading=@IsLoading>
    @if (formState.Value.Form != null && templateState.Value.Template != null)
    {
        <FormEditor Form=@formState.Value.Form
            Saved=@HandleSave
            Published=@HandlePublish
            CanSave=@CanSave
            WorkflowLayout=@Layout
            Template=@templateState.Value.Template
            AllTemplates="@templatesState.Value.Templates"
            SupportedLanguageCodes="@languagesState.Value.Codes"
            TemplateSwitched="@HandleTemplateSwitched"
            TemplateSaved=@HandleUpdateTemplate></FormEditor>
    }
</RadzenCardLoader>

@code {
    [Parameter] public string Id { get; set; }
    [Parameter] public bool CanSave { get; set; }
    private ActionState<FormRecord, bool> _updateForm;
    private ActionState<FormRecord, FormRecord> _publishForm;
    private ActionState<Template, bool> _updateTemplate;

    private bool IsLoading
    {
        get
        {
            return workflowLayoutListState.Value.IsLoading || formState.Value.IsLoading;
        }
    }

    public WorkflowLayout Layout
    {
        get
        {
            return workflowLayoutListState.Value.Values?.SingleOrDefault(l => l.SourceFormCorrelationId == formState.Value.Form.CorrelationId);
        }
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        if (!string.IsNullOrWhiteSpace(Id))
        {
            dispatcher.Dispatch(new GetFormAction { Id = Id });
        }
    }

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
        {
            SubscribeToAction<SwitchTemplateSuccessAction>((act) =>
            {
                navigationManager.NavigateTo(navigationManager.Uri, true);
            });
            SubscribeToAction<UpdateFormSuccessAction>((act) =>
            {
                _updateForm.Callback(true);
                StateHasChanged();
            });
            SubscribeToAction<PublishFormSuccessAction>((act) =>
            {
                _publishForm.Callback(act.Form);
                StateHasChanged();
            });
            SubscribeToAction<UpdateTemplateSuccessAction>((act) =>
            {
                _updateTemplate.Callback(true);
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.TemplateUpdated });
                StateHasChanged();
            });
        }
    }

    private void HandleSave(ActionState<FormRecord, bool> state)
    {
        _updateForm = state;
        dispatcher.Dispatch(new UpdateFormAction { Id = formState.Value.Form.CorrelationId, Form = formState.Value.Form });
    }

    private void HandlePublish(ActionState<FormRecord, FormRecord> state)
    {
        _publishForm = state;
        dispatcher.Dispatch(new PublishFormAction { Id = formState.Value.Form.CorrelationId });
    }

    private void HandleTemplateSwitched(Template template)
    {
        dispatcher.Dispatch(new SwitchTemplateAction { TemplateId = template.Id });
    }

    private void HandleUpdateTemplate(ActionState<Template, bool> state)
    {
        _updateTemplate = state;
        dispatcher.Dispatch(new UpdateTemplateAction { Template = state.Content });
    }
}
